package com.warren.financial.lease.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.warren.financial.lease.realtime.bean.TransientSink;

import java.lang.reflect.Field;

/**
 * @AUTHOR warren
 * @date 2024/1/1
 * @Introduction
 **/
public class Bean2JSONUtil {

    public static <T> String bean2JSON (T obj) throws IllegalAccessException {
        JSONObject jsonObject = new JSONObject();
        // 使用反射获取类模板
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for(Field field : fields){
            TransientSink annotation = field.getAnnotation(TransientSink.class);
            if(annotation == null){
                field.setAccessible(true);
                Object value = field.get(obj);
                String name = field.getName();

                StringBuilder snakeCaseName = new StringBuilder();
                for (int i = 0; i < name.length(); i++) {
                    char c = name.charAt(i);
                    if(Character.isUpperCase(c)){
                        snakeCaseName.append("_");
                        c = Character.toLowerCase(c);
                    }
                    snakeCaseName.append(c);
                }
                jsonObject.put(snakeCaseName.toString(),value);
            }

        }
        return jsonObject.toJSONString();
    }
}
